<template>
  <a-row :gutter="[16, 16]" class="search">
    <a-col :span="4">
      <a-input v-model:value="searchInfo.username" placeholder="分类创建人" />
    </a-col>
    <a-col :span="4">
      <a-input v-model:value="searchInfo.name" placeholder="分类名" />
    </a-col>
    <a-col :span="4" class="btn">
      <a-button :icon="h(SearchOutlined)" type="primary" @click="search"
        >搜索
      </a-button>
      <a-button :icon="h(RedoOutlined)" @click="restSearch">重置</a-button>
    </a-col>
  </a-row>

  <a-row style="display: flex; align-items: center; gap: 15px; margin: 15px 0">
    <a-button type="primary" @click="add">新增</a-button>
    <a-popconfirm
      cancel-text="取消"
      ok-text="删除"
      title="是否删除?"
      @confirm="deleteFunction(toRaw(state.selectedRowKeys))"
    >
      <a-button danger>删除</a-button>
    </a-popconfirm>
    <a-button>导出</a-button>
  </a-row>

  <!--  table-->
  <a-table
    :columns="columns"
    :data-source="TableData"
    :loading="loading"
    :pagination="pagination"
    :row-selection="{
      selectedRowKeys: state.selectedRowKeys,
      onChange: onSelectChange,
    }"
    style="height: calc(100vh - 270px)"
    @change="handleTableChange"
  >
    <template #bodyCell="{ column, record }">
      <template v-if="column.key === 'cover'">
        <a-image
          v-if="record.cover"
          :src="record.cover"
          style="width: 80px; height: 60px"
        />
        <a-image
          v-else
          :width="200"
          fallback=""
          src="https://www.antdv.com/#error"
          style="height: 60px"
        />
      </template>

      <template v-if="column.key === 'status'">
        <span>
          <a-tag v-if="record.status === 1" color="geekblue">正常</a-tag>
          <a-tag v-else color="error">注销</a-tag>
        </span>
      </template>

      <template v-if="column.key === 'createDate'">
        <span>
          {{ dayjs(record.createDate).format("YYYY-MM-DD HH:mm:ss") }}
        </span>
      </template>
      <template v-if="column.key === 'action'">
        <span style="display: flex; align-items: center; gap: 15px">
          <a-button type="primary" @click="edit(record)">
            <template #icon>
              <EditOutlined />
            </template>
          </a-button>
          <a-popconfirm
            cancel-text="取消"
            ok-text="删除"
            title="是否删除该分类?"
            @confirm="deleteFunction(record.id)"
          >
            <a-button danger>
              <template #icon>
                <DeleteOutlined />
              </template>
            </a-button>
          </a-popconfirm>
        </span>
      </template>
    </template>
  </a-table>
  <!--   form-->
  <a-modal
    :title="!editId ? '新增分类' : '更新分类'"
    :open="open"
    :footer="null"
    @cancel="resetForm"
  >
    <a-form
      ref="formRef"
      :label-col="labelCol"
      :model="formState"
      :rules="rules"
      :wrapper-col="wrapperCol"
      style="margin-top: 15px"
    >
      <a-form-item ref="name" label="分类名" name="name">
        <a-input v-model:value="formState.name" placeholder="请输入分类名" />
      </a-form-item>
      <a-form-item label="分类封面" name="cover">
        <Upload v-model:FileList="formState.cover"></Upload>
      </a-form-item>
      <a-form-item label="分类描述" name="summary">
        <a-textarea
          v-model:value="formState.summary"
          placeholder="请输入分类描述"
        />
      </a-form-item>
      <a-form-item
        :wrapper-col="{ span: 14, offset: 14 }"
        style="margin-top: 15px"
      >
        <a-button @click="resetForm">重置</a-button>
        <a-button
          style="margin-left: 15px"
          type="primary"
          @click.prevent="onSubmit"
          >{{ !editId ? "创建" : "更新" }}
        </a-button>
      </a-form-item>
    </a-form>
  </a-modal>
</template>
<script setup>
import {
  DeleteOutlined,
  EditOutlined,
  RedoOutlined,
  SearchOutlined,
} from "@ant-design/icons-vue";
import { computed, h, reactive, ref, toRaw } from "vue";
import { userStore } from "@/store/modules/user.js";
import { message } from "ant-design-vue";
import { addSort, delSort, sortAll, updateSort } from "@/api/sort.js";
import dayjs from "dayjs";
import Upload from "@/components/Upload/index.vue";
const user = userStore();

// ref
const formRef = ref(null);

const initSearch = {
  username: undefined,
  name: undefined,
};
let searchInfo = reactive({ ...initSearch });
let TableData = ref([]);
const formState = reactive({
  name: "",
  cover: "",
  summary: "",
});
const sortList = ref([]);
const state = reactive({
  selectedRowKeys: [],
});

let loading = ref(true);
let total = ref(0);
let current = ref(0);
let pageSize = ref(0);
let open = ref(false);
let editId = ref(null);

// 配置项
const columns = [
  {
    title: "封面",
    key: "cover",
    dataIndex: "cover",
  },
  {
    title: "分类名",
    key: "name",
    dataIndex: "name",
    width: 150,
  },
  {
    title: "创建人",
    key: "username",
    dataIndex: "username",
  },
  {
    title: "状态",
    key: "status",
    dataIndex: "status",
  },
  {
    title: "创建时间",
    key: "createDate",
    dataIndex: "createDate",
  },
  {
    title: "描述",
    key: "summary",
    dataIndex: "summary",
  },

  {
    title: "操作",
    key: "action",
    width: 300,
  },
];
const wrapperCol = {
  span: 13,
};
const labelCol = {
  span: 7,
};
const rules = {
  name: [
    {
      required: true,
      message: "分类名不能为空",
      trigger: "change",
    },
  ],
  summary: [
    {
      required: true,
      message: "分类描述不能为空",
      trigger: "change",
    },
  ],
};

// 获取table数据
const get_TableData = async (params) => {
  let res = await sortAll({ ...params });
  if (res && res.status === 400) return;
  TableData.value = res.data.map((item) => ({
    ...item,
    key: item.id,
  }));
  total.value = res.total;
  current.value = res.page;
  pageSize.value = res.pageSize;
  loading.value = false;
  sortList.value = res.data;
};

// 查询博客
const search = async () => {
  loading.value = true;
  if (searchInfo.username === undefined && searchInfo.name === undefined) {
    message.error("查询不能为空");
    return;
  }
  let info = toRaw(searchInfo);
  await get_TableData({ ...info });
};

// 重置查询
const restSearch = async () => {
  loading.value = true;
  Object.assign(searchInfo, initSearch);
  await get_TableData();
};

// 打开新增弹窗
const add = () => {
  editId.value = null;
  open.value = true;
};
// 打开编辑弹窗
const edit = (record) => {
  editId.value = record.id;
  open.value = true;
  handeEditData(record);
};

// 勾选删除id
const onSelectChange = (selectedRowKeys) => {
  state.selectedRowKeys = selectedRowKeys;
};

// 删除分类
const deleteFunction = async (params) => {
  let res = await delSort({ id: params });
  await get_TableData();
  message.success(res.data);
};

// 提交
const onSubmit = () => {
  formRef.value
    .validate()
    .then(async () => {
      let info = toRaw(formState);
      await requestFunction(info);
      resetForm();
      await get_TableData();
      open.value = false;
    })
    .catch((error) => {
      console.log("error", error);
    });
};

// 处理请求
const requestFunction = async (params) => {
  let res = null;
  if (!editId.value) res = await addSort({ ...params, user: user.user_id });
  else res = await updateSort({ ...params, id: editId.value });
  if (res && res.status != 400) message.success(res.data);
  else message.error(res.data);
};

// 分页
const pagination = computed(() => ({
  total: total.value,
  current: current.value,
  pageSize: pageSize.value,
  showTotal: (total) => `总共 ${total} 项`,
  defaultPageSize: 10,
  pageSizeOptions: ["5", "10", "15", "20"], // 可不设置使用默认
}));

// 点击分页
const handleTableChange = (pag, filters, sorter) => {
  current.value = pag.current;
  pageSize.value = pag.pageSize;
  get_TableData({ page: current.value, pageSize: pageSize.value });
};

// 重置表单
const resetForm = () => {
  handeEditData({
    name: "",
    cover: "",
    summary: "",
  });
  open.value = false;
};

// 处理表单回显数据
const handeEditData = (obj) => {
  if (obj) {
    for (let key in obj) {
      if (formState.hasOwnProperty(key)) {
        formState[key] = obj[key];
      }
    }
  }
};

get_TableData();
</script>

<style lang="scss" scoped>
.search {
  .btn {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: space-evenly;
    gap: 15px;
  }
}

.topActive {
  background-color: #63a35c;
  color: #fff;
}
</style>
